//
//  FoundController.m
//  BuyOfNoWane
//
//  Created by qianfeng02 on 15/7/3.
//  Copyright (c) 2015年 迷茫的尧尧. All rights reserved.
//

#import "FoundController.h"
#import "FoundCell.h"
#import "MMProgressHUD.h"
#import "DetaiController.h"
@interface FoundController ()<UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic ,strong)NSMutableArray *dataArray;
@property (nonatomic ,strong)UICollectionView *collectionView;
@property (nonatomic)BOOL isRefreshing;
@property (nonatomic)BOOL isLoadMore;
@property(nonatomic ,strong)AFHTTPRequestOperationManager *manager;

@end

@implementation FoundController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createCollectionView];
    [self firstDownload];
    [self creatRefreshView];
    [self addTitleViewWithTitle:@"心发现"];
     self.collectionView.backgroundColor=[UIColor clearColor];
    //self.view.backgroundColor=[UIColor purpleColor];
    //self.layout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width-20) /2, ([UIScreen mainScreen].bounds.size.height-140) /3);
    
    
}
-(void)createCollectionView
{
    _dataArray = [[NSMutableArray alloc]init];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    // 设置行间距
    flowLayout.minimumLineSpacing = 5;
    // 设置item之间间距，实际间隔需要根据item的size和edgesInsets的值来调节
    flowLayout.minimumInteritemSpacing = 5;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-49-64) collectionViewLayout:flowLayout];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    [_collectionView registerNib:[UINib nibWithNibName:@"FoundCell" bundle:nil] forCellWithReuseIdentifier:@"FoundCell"];
    [self.view addSubview:_collectionView];
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
}
#pragma mark -delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FoundCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"FoundCell" forIndexPath:indexPath];
    AppModel *model=_dataArray[indexPath.row];
    [cell showDataWithModel:model indexPath:indexPath];
    return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((kScreenSize.width-15)/2,230);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",_dataArray[indexPath.row]);
    DetaiController *detail=[[DetaiController alloc]init];
    AppModel *model=_dataArray[indexPath.row];
    detail.categoryID=model.article_id;
    detail.categoryType=self.categoryType;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)creatRefreshView
{
    //下拉刷新
    __weak typeof (self)weakSelf=self;
    [self.collectionView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;
        weakSelf.limitNum=20;
        NSString *url=nil;
        url=[NSString stringWithFormat:weakSelf.requestUrl,weakSelf.limitNum];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
        
    }];
    //上啦加载更多
    [self.collectionView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore=YES;
        weakSelf.limitNum +=20;
        NSString *url=nil;
        url=[NSString stringWithFormat:weakSelf.requestUrl,weakSelf.limitNum];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
    
    }];
}
- (void)endRefreshing
{
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.collectionView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.collectionView footerEndRefreshing];
    }
}
//第一次下载
- (void)firstDownload
{
    //[self addTaskWithUrl:kFoundUrl isRefresh:NO];
    self.limitNum=20;
    NSString *url=[NSString stringWithFormat:self.requestUrl,self.limitNum];
    
    [self addTaskWithUrl:url isRefresh:NO];

}
//增加下载任务
- (void)addTaskWithUrl:(NSString *)url isRefresh:(BOOL)isRefresh
{
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleExpand];
    [MMProgressHUD showWithTitle:@"欢迎光临，正在努力加载" status:@"Loading..."];
    __weak typeof (self)weakSelf=self;
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"加载成功");
        if (responseObject) {
            [_dataArray removeAllObjects];
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dict2=dict[@"data"];
            NSArray *rowsarr=dict2[@"rows"];
            for (NSDictionary *dict1 in rowsarr) {
                AppModel *model=[[AppModel alloc]init];
                [model setValuesForKeysWithDictionary:dict1];
                [weakSelf.dataArray addObject:model];
            }
            [weakSelf.collectionView reloadData];
            [weakSelf endRefreshing];
            [MMProgressHUD dismissWithSuccess:@"OK" title:@"数据下载完成"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        [MMProgressHUD dismissWithError:nil title:@"网络故障"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
